from __future__ import absolute_import
import os
import time

from django.core.urlresolvers import reverse
from django.shortcuts import render, render_to_response, get_object_or_404
from django.utils import timezone
from django.views.generic import View, ListView, DetailView
from django.views.generic import CreateView, UpdateView, DeleteView, TemplateView
from django.views.generic.base import TemplateResponseMixin, ContextMixin
from django.views.generic.detail import SingleObjectMixin
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse, HttpResponseForbidden
from django.template import loader, Template, Context

from .models import Publisher, Book, Author


class PublisherListView(ListView):
    context_object_name = "publisher_list"
    template_name = "books/publisher_list.html"
    ## model = Publisher
    queryset = Publisher.objects.all()
    # def get_queryset(self, **kwargs):
    #     return super(PublisherListView, self).get_queryset(**kwargs)

    def get_context_data(self, **kwargs):
        context = super(PublisherListView, self).get_context_data(**kwargs)
        context['new_data'] = {}
        context['new_data']['addti1'] = "test and learn: Hello Django"
        context['new_data']['timenow'] = "test and learn:" + str(timezone.now())
        return context

    def get_object(self):
        object = super(PublisherListView, self).get_object()
        return object


class PublisherDetailView_my1(DetailView):
    context_object_name = 'publisher'
    template_name = "books/publisher_detail.html"
    queryset = Publisher.objects.all()

    def get(self, request, *args, **kwargs):
        self.object = self.get_object(queryset=Publisher.objects.all())
        print self.object
        return super(PublisherDetailView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(PublisherDetailView, self).get_context_data(**kwargs)
        context['books'] = Book.objects.filter(publisher=self.object)
        context['Custom'] = "my custom data."
        print context
        return context


class PublisherDetailView(SingleObjectMixin, ListView):
    paginate_by = 2
    template_name = "books/publisher_detail2.html"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object(queryset=Publisher.objects.all())
        print "debug?? 1 ", time.ctime()
        return super(PublisherDetailView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(PublisherDetailView, self).get_context_data(**kwargs)
        context['publisher'] = self.object
        print context
        print "debug?? 2 ", time.ctime()
        print self.request
        return context

    def get_queryset(self):
        return self.object.book_set.all()


class PublisherBookList(ListView):
    template_name = "books/books_by_publisher.html"

    def get_queryset(self):
        ## self.args[num]
        self.publisher = get_object_or_404(Publisher, name=self.args[0])
        ## self.kwargs['key']
        # self.publisher = get_object_or_404(Publisher, name=self.kwargs['arg1'])
        # return Book.objects.filter(publisher=self.publisher)
        return self.publisher.book_set.all()

    def get_context_data(self, **kwargs):
        context = super(PublisherBookList, self).get_context_data(**kwargs)
        context['publisher'] = self.args[0]
        return context


class AuthorDetailView(DetailView):
    template_name = "books/author_detail.html"
    ### model OR queryset OR get_queryset()
    # model = Author
    # queryset = Author.objects.all()
    def get_queryset(self, **kwargs):
        print "debug: 2", self.kwargs
        return Author.objects.all()

    def get_object(self):
        self.object = super(AuthorDetailView, self).get_object()
        # object.OPERATION
        print "debug: 3", self.object.headshot
        print type(self.object)
        return self.object

    def get_context_data(self, **kwargs):
        context = super(AuthorDetailView, self).get_context_data(**kwargs)
        context['books'] = Book.objects.filter(authors=self.object)
        print "debug: 4", "context: %d vars" % len(context)
        return context

    def get(self, request, *args, **kwargs):
        # self.object = self.get_object(queryset=Author.objects.all())
        # self.object = self.get_object()
        print "debug: 1", "request: %d vars" % len(str(request).split('.'))
        print "request.user: ", request.user
        return super(AuthorDetailView, self).get(request, *args, **kwargs)


class AuthorListView(ListView):
    template_name = 'books/author_list.html'
    context_object_name = 'author_list'
    queryset = Author.objects.all()


class AuthorCreateView(CreateView):
    from .forms_author import AuthorForm
    form_class = AuthorForm
    model = Author
    fields = ['salutation', 'name', 'sex', 'email', 'headshot',]
    template_name = 'books/author_form.html'

    ###??? if self.form_valid(form) WRONG ????
    # def post(self, request, *args, **kwargs):
    #     form = self.form_class(request.POST)
    #     # if form.is_valid():
    #     #     for key in request.POST:
    #     #         print key, request.POST[key]
    #     #         print request.FILES
    #     print "dir(form): ", dir(form)
    #     if self.form_valid(form):
    #         return super(AuthorCreateView, self).post(request, *args, **kwargs)
    #     return render(request, self.template_name, {'form': form})

    def form_valid(self, form):
        print "form:", form
        print "form.instance: ", form.instance
        return super(AuthorCreateView, self).form_valid(form)
        #return True


class AuthorUpdateView(UpdateView):
    model = Author
    template_name_suffix = "_update_form"
    fields = ['salutation', 'name', 'sex', 'email', 'headshot',]

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            print "debug: post", "user isn't authenticated"
            return HttpResponseForbidden()
        self.object = self.get_object()
        print("debug_AuthorUpdateView:" + str(dir(request.POST)))
        return super(AuthorUpdateView, self).post(request, *args, **kwargs)

    def get_success_url(self):
        return reverse(viewname='book:author_detail',
                       kwargs={'pk': self.object.pk})


class AuthorDeleteView(DeleteView):
    model = Author
    success_url = reverse_lazy('book:author_list')

    def get(self, request, *args, **kwargs):
        print args
        print kwargs
        return super(AuthorDeleteView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        print args
        print kwargs
        ##delete author's headshot
        delete_auth = Author.objects.get(**kwargs)
        delete_auth.headshot.delete()
        return super(AuthorDeleteView, self).post(request, *args, **kwargs)


class BookListView(ListView):
    model = Book
    # queryset = Book.objects.filter(publisher=pk)
    context_object_name = "book_list"
    template_name = 'books/books_by_publisher.html'

    def get_context_data(self, **kwargs):
        context = super(BookListView, self).get_context_data(**kwargs)
        #print context['book_list'][0].authors_list()
        return context


class BookDetailView(DetailView):
    model = Book
    template_name = 'books/book_detail.html'
    context_object_name = "book"

    def get_context_data(self, **kwargs):
        context = super(BookDetailView, self).get_context_data(**kwargs)
        # print (context['book'].title)
        # print (context['book'].publisher)
        # print (context['book'].publication_date)
        return context

    def get(self, request, *args, **kwargs):
        return super(BookDetailView, self).get(request, *args, **kwargs)


class MyCustomView(View):
    html_name = "books/custom.html"
    greeting = "Good Day_Class Based View"

    def get(self, *args, **kwargs):
        cont = self.request.META
        cont['CUSTOM_CONTEXT'] = self.greeting
        #print cont
        return render_to_response(self.html_name,
                                  {'context': cont})


class Inheri1MyCustomView(MyCustomView):
    html_name = "books/about.html"
    greeting = "About Page of Inheritance"


class HomePageView(TemplateView):
    template_name = "books/custom.html"
    custom_msg = "Here is HomePage"

    def get_context_data(self, **kwargs):
        #context = super(HomePageView, self).get_context_data(**kwargs)
        cont = {}
        cont = self.request.META
        cont['CUSTOM_CONTEXT'] = self.custom_msg
        return cont

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response({'context': context})


class AboutView(HomePageView):
    template_name = "books/about.html"
    custom_msg = "Here is AboutPage"


#class MyCustomView2(View, ContextMixin, TemplateResponseMixin):
class MyCustomView2(TemplateResponseMixin, ContextMixin, View):
    template_name = "books/custom.html"

    def get_context_data(self, **response_kwargs):
        context = super(MyCustomView2, self).get_context_data(
            **response_kwargs)
        context['REMOTE_ADDR'] = self.request.META['REMOTE_ADDR']
        context['HTTP_USER_AGENT'] = self.request.META['HTTP_USER_AGENT']
        context['CUSTOM_CONTEXT'] = 'my custom context'
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        #print(context)
        return self.render_to_response({'context': context})


def viewfun(request):
    html_content = """
    <html><head><title>custom-view2</title></head><body>user-agent: <b>%s</b> <p>remote-addr: <i>%s</i></body></html>
    """
    return HttpResponse(html_content % (request.META['HTTP_USER_AGENT'],
                                        request.META['REMOTE_ADDR'],
                                        ))

def directory_index_my(request):
    path = "love"
    fullpath = "/home/"
    DEFAULT_DIRECTORY_INDEX_TEMPLATE = """
    {% load i18n %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Language" content="en-us" />
    <meta name="robots" content="NONE,NOARCHIVE" />
    <title>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</title>
    </head>
    <body>
    <h1>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</h1>
    <ul>
    {% ifnotequal directory "/" %}
    <li><a href="../">../</a></li>
    {% endifnotequal %}
    {% for f in file_list %}
    <li><a href="{{ f|urlencode }}">{{ f }}</a></li>
    {% endfor %}
    </ul>
    </body>
    </html>
    """
    t = Template(DEFAULT_DIRECTORY_INDEX_TEMPLATE,
                 name='Default directory index template')
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory' : path + '/',
        'file_list' : files,
    })
    return HttpResponse(t.render(c))
